package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.json.JSON;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.mapper.*;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by zhuo.shi on 2016/10/18.
 *
 * 俱乐部活动、赛事、提现资金统计定时任务，每日凌晨执行
 */
@Component
public class ClubFinanceSummaryJob implements JobRunner {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private TbClubWithdrawalsRecordMapper clubWithdrawalsRecordMapper;
    @Autowired
    private TbClubOnlineAccountMapper clubOnlineAccountMapper;
    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private TbClubFinanceDailyReportMapper clubFinanceDailyReportMapper;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubOnlineAccountStreamMapper clubOnlineAccountStreamMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;

    private static Logger logger = Logger.getLogger(ClubFinanceSummaryJob.class);

    @Override
    public Result run(JobContext jobContext) throws Throwable {

        logger.warn("开始统计俱乐部财务，当前时间：" + DateTimeUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", new Date()));
        Date endTime = new Date();
        List<TbClub> resultClubList = clubMapper.selectByExample(new TbClubExample());
        logger.warn("要统计的俱乐部数量:" + resultClubList.size());
        for (TbClub club: resultClubList) {
            logger.warn("clubID:" + club.getId());
            Date startTime = getLastSummaryTime(club.getId());
            TbClubFinanceDailyReport report = new TbClubFinanceDailyReport();
            report = calculateClubDailyFinanceReport(club.getId(), startTime, endTime, report);
            TbClubWithdrawalsRecordExample recordExample = new TbClubWithdrawalsRecordExample();
            recordExample.createCriteria()
                    .andClubIdEqualTo(club.getId())
                    .andCreateTimeGreaterThan(startTime)
                    .andCreateTimeLessThanOrEqualTo(endTime);
            List<TbClubWithdrawalsRecord> resultList1 = clubWithdrawalsRecordMapper.selectByExample(recordExample);
            BigDecimal withdrawAmount_S_total = BigDecimal.ZERO;
            for (TbClubWithdrawalsRecord record : resultList1){
                withdrawAmount_S_total= withdrawAmount_S_total.add(record.getMoney());
            }
            report.setAlreadyWithdrawAmount(withdrawAmount_S_total);   //提现成功金额
            //还未提现金额
            TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
            example.createCriteria()
                    .andClubIdEqualTo(club.getId())
                    .andCreateTimeGreaterThan(startTime)
                    .andCreateTimeLessThanOrEqualTo(endTime);
            List<TbClubActivitySettlement> list = clubActivitySettlementMapper.selectByExample(example);
            BigDecimal withdrawAmount_N_total = BigDecimal.ZERO;
            for (TbClubActivitySettlement settlement : list){
                withdrawAmount_N_total = withdrawAmount_N_total.add(settlement.getDealMoney());
            }
            report.setApplyWithdrawAmount(withdrawAmount_N_total.subtract(report.getAlreadyWithdrawAmount()));
            //费用是0则不录入
            if(bigDecimalZero(report.getAlreadyWithdrawAmount())
                    && bigDecimalZero(report.getApplyWithdrawAmount())
                    && bigDecimalZero(report.getBalanceAmount())
                    && bigDecimalZero(report.getCouponAmount())
                    && bigDecimalZero(report.getEggAmount())
                    && bigDecimalZero(report.getPayAmount()))
            {
                logger.info("clubId：" + club.getId() + "还未觉醒，失格！");
                continue;
            }
            report.setClubId(club.getId());
            report.setClubName(club.getClubName());
            Integer uid = club.getUid();
            report.setUid(uid);
            report.setCreateTime(endTime);
            report.setUpdateTime(endTime);
            report.setCityId(club.getCityId());
            APIResponse<RespUserInfoBase> response = userServiceFacade.queryUserInfo(uid);
            if (response != null && response.getData() != null) {
                report.setPhone(response.getData().getMobile());
            }
            int ret = clubFinanceDailyReportMapper.insertSelective(report);
            logger.warn("ClubFinanceSummaryJob, clubId=" + club.getId()
                    + ", 时间：" + DateTimeUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", startTime) + " - " + DateTimeUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", endTime)
                        + ", 统计结果：" + JSON.toJSONString(report));
            }

        return new Result(Action.EXECUTE_SUCCESS);
    }

    private boolean bigDecimalZero(BigDecimal date)
    {
        if(null == date || date.compareTo(BigDecimal.ZERO) == 0)
        {
            return true;
        }
        return false;
    }

    private TbClubFinanceDailyReport calculateClubDailyFinanceReport(int clubId, Date startTime, Date endTime, TbClubFinanceDailyReport report){
        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andCreateTimeGreaterThan(startTime)
                .andCreateTimeLessThanOrEqualTo(endTime);
        List<TbClubActivitySettlement> resultList = clubActivitySettlementMapper.selectByExample(example);

        BigDecimal balanceAmount = BigDecimal.ZERO;
        BigDecimal eggAmount = BigDecimal.ZERO;
        BigDecimal payAmount = BigDecimal.ZERO;
        logger.info("调测：" + JSONObject.toJSONString(resultList));
        for (TbClubActivitySettlement settlement : resultList){
            BigDecimal orderMoney = settlement.getDealMoney();             //活动收入总金额

            BigDecimal eggMoney = settlement.getAccumulateMoney();                               //鸟蛋抵扣
            eggAmount = eggAmount.add(eggMoney);

            BigDecimal payMoney = settlement.getPayMoney();
            logger.warn("payMoney" + payMoney);//第三方支付
            payAmount = payAmount.add(payMoney);
            logger.warn("payAmount" + payAmount);
            BigDecimal balanceMoney = orderMoney.subtract(eggMoney).subtract(payMoney);          //会费抵扣
            balanceAmount = balanceAmount.add(balanceMoney);
        }

        report.setEggAmount(eggAmount);
        report.setBalanceAmount(balanceAmount);
        report.setPayAmount(payAmount);

        return report;
    }

    private Date getLastSummaryTime(int clubId){
        TbClubFinanceDailyReportExample example = new TbClubFinanceDailyReportExample();
        example.createCriteria().andClubIdEqualTo(clubId);
        example.setOrderByClause(" id desc ");
        List<TbClubFinanceDailyReport> resultList = clubFinanceDailyReportMapper.selectByExample(example);
        if (resultList != null && resultList.size() > 0){
            Date startTime = resultList.get(0).getCreateTime();
            logger.warn("-------------clubId" + clubId + ",开始时间：" + startTime);
            return startTime;
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date t = null;
        try {
             t = sf.parse("2016-01-01 12:00:00"); //上线之前
        } catch (ParseException e) {
            e.printStackTrace();
        }
        logger.warn("-------------clubId" + clubId + ",开始时间：" + t);
        return t;
    }
}
